﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;

namespace EventScavenger
{
    public partial class ReaperServiceManagement : Form
    {
        public ReaperServiceManagement()
        {
            InitializeComponent();
        }

        private EventScavengerDAL eventScavengerDAL;
        private string serverPrefix = "Server: ";
        private bool loadingBusy = true;

        public void Show(EventScavengerDAL eventScavengerDAL)
        {
            this.eventScavengerDAL = eventScavengerDAL;
            Show(); // ShowDialog();
        }

        private void ReaperServiceManagement_Load(object sender, EventArgs e)
        {
            LoadReapers();
        }

        private void LoadReapers()
        {
            try
            {
                loadingBusy = true;
                startToolStripMenuItem.Enabled = false;
                stopToolStripMenuItem.Enabled = false;
                pauseToolStripMenuItem.Enabled = false;
                continueToolStripMenuItem.Enabled = false;

                if (eventScavengerDAL != null)
                {
                    lvwReapers.Items.Clear();
                    lvwReapers.Groups.Clear();
                    List<ReaperService> reapers = eventScavengerDAL.GetReaperList();
                    foreach (ReaperService reaper in reapers)
                    {
                        ListViewItem lvi = new ListViewItem(reaper.ServerName);

                        lvi.ImageIndex = 0;
                        //if (reaper.Enabled)
                        //    lvi.ForeColor = SystemColors.WindowText;
                        //else
                        //    lvi.ForeColor = Color.Gray;

                        ListViewGroup lvg = (from ListViewGroup lg in lvwReapers.Groups
                                             where lg.Header == serverPrefix + reaper.ServerName
                                             select lg).FirstOrDefault();
                        if (lvg == null)
                        {
                            lvg = new ListViewGroup(serverPrefix + reaper.ServerName);
                            lvwReapers.Groups.Add(lvg);
                        }
                        lvi.Group = lvg;
                        lvi.Tag = reaper;
                        lvwReapers.Items.Add(lvi);
                    }
                }
                loadingBusy = false;
                timerCheckServiceState.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void refreshToolStripButton_Click(object sender, EventArgs e)
        {
            LoadReapers();
        }
        private void lvwReapers_SelectedIndexChanged(object sender, EventArgs e)
        {
            toolStripButtonEdit.Enabled = lvwReapers.SelectedItems.Count == 1;
            toolStripButtonRemove.Enabled = lvwReapers.SelectedItems.Count > 0;
            editToolStripMenuItem.Enabled = lvwReapers.SelectedItems.Count == 1;
            removeToolStripMenuItem.Enabled = lvwReapers.SelectedItems.Count > 0;
            enabledToolStripMenuItem.Enabled = lvwReapers.SelectedItems.Count > 0;
            enabledToolStripMenuItem.Checked = false;

            startToolStripMenuItem.Enabled = false;
            stopToolStripMenuItem.Enabled = false;
            pauseToolStripMenuItem.Enabled = false;
            continueToolStripMenuItem.Enabled = false;

            foreach (ListViewItem lvi in lvwReapers.SelectedItems)
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //enabledToolStripMenuItem.Checked = rs.Enabled;
                    //if (rs.Enabled)
                    //{
                    //    if (lvi.ImageIndex == 1)
                    //        startToolStripMenuItem.Enabled = true;
                    //    else if (lvi.ImageIndex == 3)
                    //    {
                    //        stopToolStripMenuItem.Enabled = true;
                    //        pauseToolStripMenuItem.Enabled = true;
                    //    }
                    //    else if (lvi.ImageIndex == 4)
                    //    {
                    //        continueToolStripMenuItem.Enabled = true;
                    //    }
                    //}
                }
            }
        }

        private void timerCheckServiceState_Tick(object sender, EventArgs e)
        {
            timerCheckServiceState.Enabled = false;
            //if (!loadingBusy)
            {
                foreach (ListViewItem lvi in lvwReapers.Items)
                {                    
                    lvi.ImageIndex = GetServiceState(lvi);
                }
            }
        }

        private int GetServiceState(ListViewItem lvi)
        {
            try
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //if (rs.Enabled)
                    //{
                    //    ServiceController sc = new ServiceController(rs.ServiceName, rs.ServerName);
                    //    if (sc.Status == ServiceControllerStatus.Running)
                    //        return 3;
                    //    else if (sc.Status == ServiceControllerStatus.Stopped)
                    //        return 1;
                    //    else if (sc.Status == ServiceControllerStatus.Paused)
                    //        return 4;
                    //    else
                    //        return 2;
                    //}
                }
            }
            catch
            {
                return 0; //Unknown
            }
            return 0;
        }

        #region Context menu events
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwReapers.SelectedItems)
            {
                if (lvi.ImageIndex == 1)
                {
                    AttemptServiceStart(lvi);
                }
            }
        }
        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwReapers.SelectedItems)
            {
                if (lvi.ImageIndex == 3)
                {
                    AttemptServiceStop(lvi);
                }
            }
            timerCheckServiceState.Enabled = true;
        }
        private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwReapers.SelectedItems)
            {
                if (lvi.ImageIndex == 3)
                {
                    AttemptServicePause(lvi);
                }
            }
            timerCheckServiceState.Enabled = true;
        }
        private void continueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwReapers.SelectedItems)
            {
                if (lvi.ImageIndex == 4)
                {
                    AttemptServiceContinue(lvi);
                }
            }
            timerCheckServiceState.Enabled = true;
        }
        private void toolStripButtonRemove_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove the selected entry(s)?\r\nThis will NOT remove the installed service itself", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                foreach (ListViewItem lvi in lvwReapers.SelectedItems)
                {
                    if (lvi.Tag is ReaperService)
                    {
                        ReaperService rs = (ReaperService)lvi.Tag;
                        eventScavengerDAL.DeleteReaper(rs);
                    }
                }
                LoadReapers();
            }
        }
        #endregion


        #region Service management
        private void AttemptServiceStart(ListViewItem lvi)
        {
            try
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //if (rs.Enabled)
                    //{
                    //    ServiceController sc = new ServiceController(rs.ServiceName, rs.ServerName);
                    //    if (sc.Status == ServiceControllerStatus.Stopped)
                    //    {
                    //        sc.Start();
                    //        lvi.ImageIndex = 3;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Stop", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void AttemptServiceStop(ListViewItem lvi)
        {
            try
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //ServiceController sc = new ServiceController(rs.ServiceName, rs.ServerName);
                    //if (rs.Enabled)
                    //{
                    //    if (sc.Status == ServiceControllerStatus.Running)
                    //    {
                    //        sc.Stop();
                    //        lvi.ImageIndex = 1;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Stop", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void AttemptServicePause(ListViewItem lvi)
        {
            try
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //ServiceController sc = new ServiceController(rs.ServiceName, rs.ServerName);
                    //if (rs.Enabled)
                    //{
                    //    if (sc.Status == ServiceControllerStatus.Running)
                    //    {
                    //        sc.Pause();
                    //        lvi.ImageIndex = 4;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Stop", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void AttemptServiceContinue(ListViewItem lvi)
        {
            try
            {
                if (lvi.Tag is ReaperService)
                {
                    ReaperService rs = (ReaperService)lvi.Tag;
                    //ServiceController sc = new ServiceController(rs.ServiceName, rs.ServerName);
                    //if (rs.Enabled)
                    //{
                    //    if (sc.Status == ServiceControllerStatus.Paused)
                    //    {
                    //        sc.Continue();
                    //        lvi.ImageIndex = 3;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Stop", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        #endregion

        private void toolStripButtonEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvwReapers.SelectedItems.Count == 1)
                {
                    ReaperService rs = (ReaperService)lvwReapers.SelectedItems[0].Tag;
                    ReaperServiceEdit reaperServiceEdit = new ReaperServiceEdit();
                    reaperServiceEdit.SelectedService = rs;
                    if (reaperServiceEdit.Show(eventScavengerDAL) == System.Windows.Forms.DialogResult.OK)
                    {
                        eventScavengerDAL.UpdateReaper(reaperServiceEdit.SelectedService);

                        //lvwReapers.SelectedItems[0].Text = rs.ServiceName;
                        //lvwReapers.SelectedItems[0].SubItems[1].Text = rs.CollectorName;
                        ListViewGroup lvg = (from ListViewGroup lg in lvwReapers.Groups
                                             where lg.Header == serverPrefix + rs.ServerName
                                             select lg).FirstOrDefault();
                        if (lvg == null)
                        {
                            lvg = new ListViewGroup(serverPrefix + rs.ServerName);
                            lvwReapers.Groups.Add(lvg);
                        }
                        lvwReapers.SelectedItems[0].Group = lvg;
                        //if (rs.Enabled)
                        //    lvwReapers.SelectedItems[0].ForeColor = SystemColors.WindowText;
                        //else
                        //    lvwReapers.SelectedItems[0].ForeColor = Color.Gray;
                        lvwReapers.SelectedItems[0].Tag = reaperServiceEdit.SelectedService;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripButtonNew_Click(object sender, EventArgs e)
        {
            try
            {
                ReaperServiceEdit reaperServiceEdit = new ReaperServiceEdit();
                if (reaperServiceEdit.Show(eventScavengerDAL) == System.Windows.Forms.DialogResult.OK)
                {
                    eventScavengerDAL.InsertReaper(reaperServiceEdit.SelectedService);
                    LoadReapers();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void enabledToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem lvi in lvwReapers.SelectedItems)
                {
                    if (lvi.Tag is ReaperService)
                    {
                        ReaperService rs = (ReaperService)lvi.Tag;
                        //rs.Enabled = enabledToolStripMenuItem.Checked;
                        //eventScavengerDAL.UpdateReaper(rs);
                        //if (rs.Enabled)
                        //    lvi.ForeColor = SystemColors.WindowText;
                        //else
                        //    lvi.ForeColor = Color.Gray;
                        //lvi.Tag = rs;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



    }
}
